<template>
    <div class="user-container">
        <el-card class="user-card" :body-style="{ padding: '30px' }" shadow="hover">
            <template #header>
                <div class="card-header">
                    <el-page-header icon="" :title="'用户信息'">
                        <template #icon>
                            <el-icon>
                                <User />
                            </el-icon>
                        </template>
                    </el-page-header>
                </div>
            </template>

            <el-skeleton v-if="loading" :rows="6" animated style="padding: 20px" />

            <el-scrollbar v-else height="auto">
                <div class="user-info-container">
                    <div class="avatar-container">
                        <el-avatar :size="120" shape="circle" :fit="'cover'" :src="userInfo.avatar || defaultAvatar" />
                        <el-text class="user-id" size="small" type="info" disabled>ID: {{ userInfo.id }}</el-text>
                        <el-upload v-if="isEditing" class="avatar-upload" action="#" :auto-upload="false"
                            :show-file-list="false" :on-change="handleAvatarChange" accept="image/*">
                            <el-button size="small" type="primary" round class="avatar-button">
                                <el-icon>
                                    <Upload />
                                </el-icon>
                                <span>更换头像</span>
                            </el-button>
                        </el-upload>
                    </div>

                    <div class="info-container">
                        <el-divider content-position="left">
                            <el-tag effect="dark" type="info" size="large" round>
                                <el-icon>
                                    <InfoFilled />
                                </el-icon>
                                <span style="margin-left: 5px">基本信息</span>
                            </el-tag>
                        </el-divider>

                        <el-form :model="userInfo" label-position="left" label-width="80px" :disabled="!isEditing"
                            class="user-form">
                            <el-row :gutter="20">
                                <el-col :span="12">
                                    <el-form-item label="用户名">
                                        <el-input v-model="userInfo.username" placeholder="用户名" clearable>
                                            <!--<template #prefix>
                                                <el-icon>
                                                    <User />
                                                </el-icon>
                                            </template>-->
                                        </el-input>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="身份" :disabled="true">
                                        <el-select v-model="userInfo.role" placeholder="用户身份" disabled class="w-100">
                                            <el-option label="管理员" :value=1></el-option>
                                            <el-option label="租客" :value=2></el-option>
                                            <el-option label="房东" :value=3></el-option>
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                            </el-row>

                            <el-row :gutter="20">
                                <el-col :span="12">
                                    <el-form-item label="年龄">
                                        <el-input v-model="userInfo.age" placeholder="未知" type="number" class="w-100" @input="handleAgeInput">
                                        </el-input>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="性别">
                                        <el-select v-model="userInfo.gender" placeholder="请选择性别" class="w-100">
                                            <el-option label="男" :value=1></el-option>
                                            <el-option label="女" :value=2></el-option>
                                            <el-option label="其他" :value=3></el-option>
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                            </el-row>

                            <el-divider content-position="left">
                                <el-tag effect="dark" type="info" size="large" round>
                                    <el-icon>
                                        <Message />
                                    </el-icon>
                                    <span style="margin-left: 5px">联系方式</span>
                                </el-tag>
                            </el-divider>

                            <el-form-item label="电话">
                                <el-input v-model="userInfo.phone" placeholder="电话号码" clearable>
                                    <template #prefix>
                                        <el-icon>
                                            <Phone />
                                        </el-icon>
                                    </template>
                                </el-input>
                            </el-form-item>

                            <el-form-item label="邮箱">
                                <el-input v-model="userInfo.email" placeholder="电子邮箱" clearable>
                                    <template #prefix>
                                        <el-icon>
                                            <Message />
                                        </el-icon>
                                    </template>
                                </el-input>
                            </el-form-item>

                            <el-divider content-position="left">
                                <el-tag effect="dark" type="info" size="large" round>
                                    <el-icon>
                                        <Document />
                                    </el-icon>
                                    <span style="margin-left: 5px">个人简介</span>
                                </el-tag>
                            </el-divider>

                            <el-form-item label="个人简介">
                                <el-input v-model="userInfo.description" type="textarea" :rows="4" placeholder="个人简介"
                                    resize="none" show-word-limit maxlength="500"></el-input>
                            </el-form-item>
                        </el-form>
                    </div>
                </div>

                <div class="action-buttons">
                    <el-button v-if="!isEditing" type="primary" @click="startEditing" round :icon="Edit">
                        编辑信息
                    </el-button>
                    <template v-else>
                        <el-button type="success" @click="saveUserInfo" round :icon="Check">
                            保存
                        </el-button>
                        <el-button type="danger" @click="cancelEditing" round :icon="Close">
                            取消
                        </el-button>
                    </template>
                </div>
            </el-scrollbar>
        </el-card>
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import apiClient from '@/api/api'
import {
    User, Upload, InfoFilled, Message, Phone, Document,
    Edit, Check, Close
} from '@element-plus/icons-vue'

const router = useRouter()
const loading = ref(true)
const isEditing = ref(false)
// 默认头像
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
// 上传的头像文件
const avatarFile = ref<File | null>(null)
// 用户信息对象
const userInfo = reactive({
    id: 0,
    username: '',
    age: 0,
    gender: '',
    phone: '',
    email: '',
    avatar: defaultAvatar,
    description: '',
    role: 0
})

// 处理头像变更
const handleAvatarChange = async (uploadFile:any) => {
    if (!uploadFile || !uploadFile.raw) {
        ElMessage.error('上传文件无效！')
        return
    }
    const file = uploadFile.raw
    // 验证文件类型
    const isImage = file.type && file.type.startsWith('image/')
    if (!isImage) {
        ElMessage.error('请上传图片文件！')
        return
    }

    // 验证文件大小（限制为2MB）
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isLt2M) {
        ElMessage.error('图片大小不能超过2MB！')
        return
    }
    avatarFile.value = file
    // 创建文件的URL并赋值给avatar
    const fileReader = new FileReader()
    fileReader.onload = (e) => {
        userInfo.avatar = e.target?.result as string
    }
    fileReader.readAsDataURL(file)
}

// 备份原始用户信息，用于取消编辑时恢复
const originalUserInfo = ref({})

// 获取用户信息
const getUserInfo = async () => {
    loading.value = true

    // 调用API获取用户详细信息
    await apiClient.get('/user/info')
        .then(response => {
            const data = response.data
            if (data.code === 1) {
                // 更新用户信息
                Object.assign(userInfo, data.data)
                // 保存原始信息的副本
                originalUserInfo.value = JSON.parse(JSON.stringify(userInfo))
            } else {
                ElMessage({
                    type: 'error',
                    message: data.message || '获取用户信息失败'
                })
                // 清除本地存储的token和用户ID
                localStorage.removeItem('token')
                localStorage.removeItem('userId')
                localStorage.removeItem('userRole')
                router.push('/login')
            }
        })
        .catch(error => {
            console.error('获取用户信息出错:', error)
            ElMessage({
                type: 'error',
                message: '获取用户信息失败，请稍后再试'
            })
        })
    loading.value = false
}

// 开始编辑
const startEditing = () => {
    isEditing.value = true
    // 保存当前信息的副本，用于取消编辑时恢复
    originalUserInfo.value = JSON.parse(JSON.stringify(userInfo))
}

// 取消编辑
const cancelEditing = () => {
    isEditing.value = false
    // 恢复原始信息
    Object.assign(userInfo, originalUserInfo.value)
}

// 保存用户信息
const saveUserInfo = async () => {
    try {
        // 如果有新头像需要上传
        if (avatarFile.value && userInfo.avatar !== defaultAvatar) {
            const formData = new FormData()
            formData.append('file', avatarFile.value)
            const avatarResponse = await apiClient.post('/user/avatar/upload', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data'
                }
            })
            if (avatarResponse.data.code !== 1) {
                throw new Error(avatarResponse.data.message || '头像上传失败')
            }
            userInfo.avatar = avatarResponse.data.data.avatar
        }

        // 更新用户信息
        const response = await apiClient.put('/user/update', userInfo)
        const data = response.data

        if (data.code === 1) {
            ElMessage({
                type: 'success',
                message: '用户信息更新成功'
            })
            isEditing.value = false
            // 更新原始信息的副本
            originalUserInfo.value = JSON.parse(JSON.stringify(userInfo))
        } else {
            throw new Error(data.message || '更新用户信息失败')
        }
    } catch (error) {
        console.error('更新用户信息出错:', error)
        ElMessage({
            type: 'error',
            message: '更新用户信息失败，请稍后再试'
        })
    }
}
// 处理年龄输入
const handleAgeInput = (value: string) => {
    const age = parseInt(value)
    if (isNaN(age)) {
        userInfo.age = 1
        ElMessage.warning('请输入有效的年龄')
        return
    }
    if (age < 1) {
        userInfo.age = 1
        ElMessage.warning('年龄不能小于1岁')
    } else if (age > 120) {
        userInfo.age = 120
        ElMessage.warning('年龄不能大于120岁')
    } else {
        userInfo.age = age
    }
}
// 组件挂载时获取用户信息
onMounted(async () => {
    document.title = '用户信息'
    await getUserInfo()
})
</script>

<style scoped>
.user-container {
    display: flex;
    justify-content: center;
    padding: 30px;
}

.user-card {
    width: 100%;
    max-width: 900px;
    transition: all 0.3s ease;
    border-radius: 12px;
    overflow: hidden;
    background-color: #ffffff;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.user-card:hover {
    box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
    display: flex;
    align-items: center;
    padding: 10px 0;
    color: #303133;
}

.user-info-container {
    display: flex;
    flex-direction: row;
    margin-bottom: 30px;
    gap: 40px;
    padding: 20px 0;
}

.avatar-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    min-width: 150px;
}

.avatar-container .el-avatar {
    border: 4px solid #fff;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
    background-color: #f0f2f5;
}

.avatar-container .el-avatar:hover {
    transform: scale(1.05);
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.15);
}

.avatar-button {
    margin-top: 15px;
    transition: all 0.3s ease;
    background-color: #409eff;
    border-color: #409eff;
    color: #ffffff;
}

.avatar-button:hover {
    background-color: #66b1ff;
    border-color: #66b1ff;
}

.info-container {
    flex: 1;
    padding: 10px;
}

.user-form .el-form-item {
    margin-bottom: 22px;
}

.user-form .el-input-number,
.user-form .el-select,
.user-form .el-input {
    width: 100%;
}

.user-form .el-input__inner {
    color: #606266;
}

.user-form .el-input__inner:focus {
    border-color: #409eff;
}

.w-100 {
    width: 100%;
    text-align: start;
}

.action-buttons {
    display: flex;
    justify-content: center;
    gap: 20px;
    margin-top: 30px;
    padding-bottom: 20px;
}

.action-buttons .el-button {
    min-width: 120px;
    transition: all 0.3s ease;
}

.action-buttons .el-button:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.action-buttons .el-button--primary {
    background-color: #409eff;
    border-color: #409eff;
}

.action-buttons .el-button--success {
    background-color: #67c23a;
    border-color: #67c23a;
}

.action-buttons .el-button--danger {
    background-color: #f56c6c;
    border-color: #f56c6c;
}

.el-divider {
    margin: 25px 0;
    border-color: #e4e7ed;
}

.el-tag {
    display: flex;
    align-items: center;
    padding: 8px 12px;
    background-color: #f0f2f5;
    border-color: #e4e7ed;
    color: #606266;
}

.el-form-item,
.el-input,
.el-select,
.el-input-number {
    transition: all 0.3s ease;
}

.el-input-number .el-input__inner {
    text-align: left !important;
}

.avatar-container .el-text.user-id {
    margin-top: 10px;
    color: #909399;
    font-size: 14px;
}

@media (max-width: 768px) {
    .user-info-container {
        flex-direction: column;
        gap: 20px;
    }

    .avatar-container {
        margin-right: 0;
        margin-bottom: 20px;
    }

    .user-card {
        margin: 0 10px;
    }

    .el-row {
        margin-left: 0 !important;
        margin-right: 0 !important;
    }
}

@media (max-width: 576px) {
    .el-form-item {
        margin-bottom: 15px;
    }

    .el-col {
        padding-left: 0 !important;
        padding-right: 0 !important;
    }
}
</style>